//
//  KeyIndexedArray.m
//  Source List
//
//  Created by Keith Duncan on 28/01/2009.
//  Copyright 2009 thirty-three software. All rights reserved.
//

#import "AFKeyIndexedArray.h"

@interface AFKeyIndexedArray ()
@property (readwrite, copy) NSString *key;
@end

@implementation AFKeyIndexedArray

@synthesize key=_key;

- (id)init; {
	self = [super init];
	
	_objects = [[NSMutableArray alloc] init];
	_index = [[NSMutableDictionary alloc] init];
	
	return self;
}

- (id)initWithKey:(NSString *)key {
	self = [super init];
	
	NSParameterAssert(key != nil);
	self.key = key;
	
	return self;
}

- (void)dealloc {
	[_key release];
	
	[_objects release];
	[_index release];
	
	[super dealloc];
}

- (NSUInteger)count; {
	return [_objects count];
}

- (id)objectAtIndex:(NSUInteger)index; {
	return [_objects objectAtIndex:index];
}

- (void)addObject:(id)object; {
	[_objects addObject:object];
	[_index setObject:object forKey:[object valueForKey:self.key]];
}

- (void)insertObject:(id)object atIndex:(NSUInteger)index; {
	id oldObject = [_objects objectAtIndex:index];
	[_index removeObjectForKey:[oldObject valueForKey:self.key]];
	
	[_objects insertObject:object atIndex:index];
	[_index setObject:object forKey:[object valueForKey:self.key]];
}

- (void)removeLastObject; {
	id object = [_objects lastObject];
	
	[_index removeObjectForKey:[object valueForKey:self.key]];
	[_objects removeLastObject];
}

- (void)removeObjectAtIndex:(NSUInteger)index; {
	id object = [_objects objectAtIndex:index];
	
	[_index removeObjectForKey:[object valueForKey:self.key]];
	[_objects removeObjectAtIndex:index];
}

- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)object; {
	[_objects replaceObjectAtIndex:index withObject:object];
	[_index setObject:object forKey:[object valueForKey:self.key]];
}

- (id)objectForIndexedValue:(id <NSCopying>)value; {
	return [_index objectForKey:value];
}

- (void)refreshIndex; {
	[_index removeAllObjects];
	
	for (id currentObject in _objects) [_index setObject:currentObject forKey:[currentObject valueForKey:self.key]];
}

@end
